
import json
import logging
from asgiref.sync import async_to_sync
from channels.layers import get_channel_layer
from .models import LocationRecord

logger = logging.getLogger(__name__)


def send_location_update(location_record):
    """
    发送位置更新消息到WebSocket
    
    Args:
        location_record: LocationRecord对象
    """
    try:
        # 获取通道层
        channel_layer = get_channel_layer()
        
        # 如果没有关联订单，则不发送消息
        if not location_record.order:
            return
        
        # 构建消息数据
        message = {
            'type': 'location_update',
            'data': {
                'location_id': location_record.id,
                'vehicle_id': location_record.vehicle.id,
                'order_id': location_record.order.id,
                'longitude': float(location_record.longitude),
                'latitude': float(location_record.latitude),
                'speed': float(location_record.speed) if location_record.speed else 0,
                'direction': float(location_record.direction) if location_record.direction else 0,
                'address': location_record.address,
                'timestamp': location_record.created_at.isoformat()
            }
        }
        
        # 发送消息到组
        group_name = f'order_{location_record.order.id}_tracking'
        async_to_sync(channel_layer.group_send)(
            group_name,
            message
        )
        
        logger.info(f"Location update sent to {group_name}")
    except Exception as e:
        logger.error(f"Error sending location update: {str(e)}")


def send_milestone_update(milestone):
    """
    发送里程碑更新消息到WebSocket
    
    Args:
        milestone: Milestone对象
    """
    try:
        # 获取通道层
        channel_layer = get_channel_layer()
        
        # 构建消息数据
        message = {
            'type': 'location_update',
            'data': {
                'milestone_id': milestone.id,
                'order_id': milestone.order.id,
                'milestone_type': milestone.milestone_type,
                'milestone_type_display': milestone.get_milestone_type_display(),
                'description': milestone.description,
                'longitude': float(milestone.longitude) if milestone.longitude else None,
                'latitude': float(milestone.latitude) if milestone.latitude else None,
                'address': milestone.address,
                'timestamp': milestone.created_at.isoformat()
            }
        }
        
        # 发送消息到组
        group_name = f'order_{milestone.order.id}_tracking'
        async_to_sync(channel_layer.group_send)(
            group_name,
            message
        )
        
        logger.info(f"Milestone update sent to {group_name}")
    except Exception as e:
        logger.error(f"Error sending milestone update: {str(e)}")